<template>
  <div class="LoginBox">
    <div class="box">
      <!-- 登录图片 -->
      <div class="img_box">
        <img src="../assets/login.jpg" alt />
      </div>
      <!-- 登录表单 -->
      <el-form ref="loginref" :rules="loginrules" label-width="0" class="form" :model="formdata">
        <!-- 账号 -->
        <el-form-item prop="username">
          <el-input prefix-icon="iconfont icon-user" v-model="formdata.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            type="password"
            prefix-icon="iconfont icon-3702mima"
            v-model="formdata.password"
          ></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="denglu">登录</el-button>
          <el-button type="info" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 数据绑定
      formdata: {
        username: "admin",
        password: "123456",
      },
      // 表单验证
      loginrules: {
        // 用户名验证
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 12, message: "长度在 3 到 12个字符", trigger: "blur" },
        ],
        // 密码验证
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // 重置事件
    reset() {
      this.$refs.loginref.resetFields();
    },
    denglu() {
      this.$refs.loginref.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$axios.post("login", this.formdata);
        if (res.meta.status != 200) return this.$message.error("登陆失败");
        this.$message.success("登陆成功");
        // 将token保存到sessionstorage中
        window.sessionStorage.setItem("token", res.data.token);
        this.$router.push("/home");
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.LoginBox {
  height: 100%;
  background-color: #2b4686;
  .box {
    width: 450px;
    height: 300px;
    border-radius: 5px;
    background-color: #fff;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    .img_box,
    img {
      height: 120px;
      width: 120px;
      border-radius: 50%;
    }
    .img_box {
      box-shadow: 3px 3px 2px #ccc;
      position: absolute;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
  .btns {
    display: flex;
    justify-content: center;
  }
  .form {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
  }
}
</style>
